package com.g2room.lab.graphQL;

import com.fasterxml.jackson.databind.ObjectMapper;
import graphql.ExecutionInput;
import graphql.GraphQL;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

@RestController
public class GraphQLController {
    ObjectMapper mapper = new ObjectMapper();
    @Autowired
    private GraphQL graphQL;
    @RequestMapping(value = "/graphql")
    // 这里定义的一个字符串接口所有的参数，定义对象也是可以的
    public Map<String, Object> graphql(@RequestBody String request) {
        Map<String, Object> req = null;
        try {
            req = mapper.readValue(request, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ExecutionInput executionInput = ExecutionInput.newExecutionInput()
                // 需要执行的查询语言
                .query(req.get("query").toString())
                // 执行操作的名称，默认为null
                .operationName(req.get("operationName").toString())
                // 获取query语句中定义的变量的值
                .variables((Map<String, Object>) req.get("variables"))
                .build();
        // 执行并返回结果
        return this.graphQL.execute(executionInput).toSpecification();
    }
}
